// import { EventSourcePolyfill } from 'event-source-polyfill'

import { useUserStore } from "@/store/useUserStore";
import { request } from "@/utils/axios";

import { type Data } from "@/utils/axios";

import type { SendMessageType } from "@/types/chat";
import { WSClient } from "@/utils/ws";

// 发送消息
export const sendChatMessage = (
  data: SendMessageType
): Promise<Data<object>> => {
  return request("/ai/v1/chat", "POST", data);
};

// 建立sse连接
// export const createSSE = (chatId: string) => {
//   const { token } = useUserStore.getState()
//   return new EventSourcePolyfill(`${BASE_URL}/chat/getChat/${chatId}`, {
//     headers: {
//       Authorization: token || ''
//     }
//   })
// }

export const createWS = (
  sessionId: string,
  onMessage?: (data: any) => void
) => {
  const { token } = useUserStore.getState();
  return new WSClient({
    url: `ws://58.23.74.236:40001/ai/v2/chat`,
    sessionId,
    token: token || "",
    onMessage: onMessage,
  });
};

export const sendWSMessage = (
  ws: WSClient,
  {
    message,
    sessionId,
    skillId,
    voice,
  }: {
    message: string | Blob;
    sessionId: number;
    skillId: number;
    voice?: number;
  }
) => {
  ws.send({
    message,
    sessionId,
    skillId,
    voice: voice ?? 0, // 默认 0
  });
};

export const sendAudioWSMessage = (
  ws: WSClient,
  {
    audio,
    sessionId,
    skillId,
    voice,
  }: {
    audio: Blob | ArrayBuffer;
    sessionId: number;
    skillId: number;
    voice?: number;
  }
) => {
  ws.send({
    type: "audio",
    sessionId,
    skillId,
    voice: voice ?? 0,
  });

  ws.send(audio);
};
